package com.dcy.znoa.controller.conference;

import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;
import com.dcy.znoa.common.annotation.AuthenticationAPI;
import com.dcy.znoa.common.controller.BaseController;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.excel.ExcelOutput;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.conference.model.operGuest.AddOperGuestModel;
import com.dcy.znoa.controller.conference.model.operGuest.SelectOperGuestModel;
import com.dcy.znoa.controller.conference.model.operGuest.UpdateOperGuestModel;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.conference.OperGuest;
import com.dcy.znoa.domain.conference.OperGuestVo;
import com.dcy.znoa.service.conference.OperGuestService;
import com.dcy.znoa.service.publiz.CompanyService;
import com.dcy.znoa.service.software.OperService;

/**
 * @author chenjie
 */
@Controller
@RequestMapping("operGuest")
public class OperGuestController extends BaseController {
    @Autowired
    OperGuestService operGuestService;
    
    @Autowired
    OperService operService;
    
    @Autowired
    CompanyService companyService;    
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectList")
    public JsonForList selectList(SelectOperGuestModel model) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	if (null != model.getStartTimeStr() && !model.getStartTimeStr().isEmpty()) {
			if (null == model.getEndTimeStr() || model.getEndTimeStr().isEmpty()) {
				return  new JsonForList("404","有开始时间，必需有结束时间！");
			}
		}
    	//访客列表 h5
    	Oper oper = getCurrentUser();
    	model.setCompId(oper.getCompId());
        return operGuestService.selectList(model);
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectStatusList")
    public JsonForList selectStatusList(SelectOperGuestModel model) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//访客列表 ：需要访客会见状态    app
    	Oper oper = getCurrentUser();
    	model.setCompId(oper.getCompId());
    	model.setOperId(oper.getOperId());
        return operGuestService.selectOperGuestStatusList(model);
    }
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/insert")
    public JsonCommon insert(@Valid AddOperGuestModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException, ParseException, ClientException {
        if (bindingResult.hasErrors()){
            FieldError fieldError= bindingResult.getFieldError();
            return  new JsonCommon("404",fieldError.getDefaultMessage());
        }
        
        //获取被访者
        Oper respondent = operService.getById(model.getOperId());
        if (null == respondent || respondent.getValidFlag() == 0) {
        	return  new JsonCommon("404","无此被访者");
		}
        
        Oper oper = getCurrentUser();
        model.setCreateOperId(oper.getOperId());
    	model.setCreateOperName(oper.getOperName());
        model.setCompId(respondent.getCompId()); 
        
        OperGuest operGuest = new OperGuest();
        BeanUtils.copyProperties(operGuest, model);
        
        if (operGuest.getOperId().longValue() == operGuest.getCreateOperId().longValue()) {
        	operGuest.setAuditStatus(1);    //0 TO_AUDIT  1审批通过   2拒绝
        	operGuest.setAuditComment("自动审批");
        	operGuest.setUpdateTime(operGuest.getCreateTime());
        	operGuest.setUpdateOperId(operGuest.getOperId());
        	operGuest.setUpdateOperName(operGuest.getCreateOperName());
		}
        operGuest.setGuestTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(model.getGuestTimeStr()));        
        //访问二维码
        operGuest.setQrCode(getOperGuestQrByUUId(oper.getCompId()));
        
        return operGuestService.insert(operGuest);
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/allowed")
    public JsonCommon allowed(@Valid UpdateOperGuestModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        //审批：拒绝、同意
    	if (bindingResult.hasErrors()){
            FieldError fieldError= bindingResult.getFieldError();
            return  new JsonCommon("404",fieldError.getDefaultMessage());
        }
        
    	Oper oper = getCurrentUser();
    	if (!operGuestService.canAllowed(oper.getOperId(),model.getGuestId()) ) {
    		return  new JsonCommon("404","无权审批");
		}
        model.setUpdateOperId(oper.getOperId());
        model.setUpdateOperName(oper.getOperName());
        OperGuest operGuest = new OperGuest();
        BeanUtils.copyProperties(operGuest, model);
        return operGuestService.updateById(operGuest);
    }
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/cancel")
    public JsonCommon cancel(@Valid UpdateOperGuestModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        //取消会见：发起和访客为同一人的，任何时候都可以取消；发起和访客不同的，只有被访者通过访问后，在访问时间之前可以取消
    	if (bindingResult.hasErrors()){
            FieldError fieldError= bindingResult.getFieldError();
            return  new JsonCommon("404",fieldError.getDefaultMessage());
        }
        
    	Oper oper = getCurrentUser();
        model.setUpdateOperId(oper.getOperId());
        model.setUpdateOperName(oper.getOperName());
        OperGuest operGuest = new OperGuest();
        BeanUtils.copyProperties(operGuest, model);
        operGuest.setValidFlag(0);  //取消
        return operGuestService.updateById(operGuest);
    }
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectById")
    public JsonCommon selectById(Long guestId) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//查询会见详情
    	if (guestId == null) {
    		return  new JsonCommon("404","缺少参数");
		}
    	
        return operGuestService.selectById(guestId);
    }    
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectByQrCode")
    public JsonCommon selectByQrCode(String qrCode) throws BusinessException, InvocationTargetException, IllegalAccessException {       
    	//查询会见详情
    	if ( StringUtils.isEmpty(qrCode) ) {
    		return  new JsonCommon("404","缺少参数");
		}
    	
        return operGuestService.selectByQrCode(qrCode);
    }  
    
    
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/export")
    public JsonCommon export(@Valid SelectOperGuestModel model,BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws BusinessException, InvocationTargetException, IllegalAccessException, IOException {
        
    	//访客列表 h5
    	Oper oper = getCurrentUser();
    	model.setCompId(oper.getCompId());
    	model.setPageNum(1);
    	model.setBeginSize(1);
    	JsonForList jsonForList = operGuestService.selectList(model);     
        
        List<Map<String, Object>> recordList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();//list转map
        List<OperGuestVo> list = jsonForList.getData();
        for (OperGuestVo operGuestVo :list) {
            recordList.add(OperGuestVo.toMap(operGuestVo));
        }
             
        String keys[] = {"depName","operName","phoneNo","gName","phone","credentialNo","guestTime","compName","personNo","carNo","status","createOperName","createTime","comment"};//map中的key
        String columnNames[] = {"被访人所在部门","被访人姓名"," 被访人联系方式","访客姓名","访客联系方式"," 登记身份证号","来访时间","所在公司","随行人数","车牌号码","访客状态","发起人","发起时间","备注"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "访客明细");
        
        return new JsonCommon(SUCCESS_CODE);
    }

    
  //会议二维码生成
    public static String getOperGuestQrByUUId(Long compId ) {
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if(hashCodeV < 0) {//有可能是负数
            hashCodeV = - hashCodeV;
        }
        // 0 代表前面补充0     
        // 4 代表长度为4     
        // d 代表参数为正数型
        return compId + String.format("%05d", hashCodeV);
    }
    
    
}
